<script setup lang="ts">
import { getCurrentInstance, ref, reactive, onBeforeMount } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
const { proxy } = getCurrentInstance()

/* ---- */
const userInfo = proxy.$Store.get('userInfo') || {}
const logUser = proxy.$Store.get('logUser') || {}
const WXConfig = proxy.$Store.get('WXConfig') || {}

/* --设置微信分享功能-- */
proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
  if (!obj) return
  // ----
  obj.hideMenuItem()
})

/* ---- */
const myCityData = proxy.$City
const addrIds = ref([])
// ----
const isMobile = /^(1[3456789]\d{9})$/
const form = reactive({
  name: '',
  is_default: true,
  telphone: '',
  addrCity: '',
  address: ''
})

/* ---- */
const pickerCity = ref()
const layer = ref()
const layerLoading = ref()

/* ---- */
const getFormInfo = () => {
  const forIdsData = {
    params: {
      'AddressSearch[dealer_id]': logUser.id,
      // ----
      page: 1,
      PageSize: 1000000000000
    }
  }
  proxy.$Axios.all([
    proxy.$Axios.get('address/index', forIdsData)
  ]).then(proxy.$Axios.spread((idsData) => {
    const idsItems = []
    idsData.items.forEach((item, index) => {
      idsItems.push(item.id)
    })
    addrIds.value = idsItems
  })).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // ----
  if (proxy.$route.query.id) {
    const forAddrData = { params: { 'AddressSearch[id]': proxy.$route.query.id } }
    proxy.$Axios.all([
      proxy.$Axios.get('address/index', forAddrData)
    ]).then(proxy.$Axios.spread((addrData) => {
      const AData = addrData.items[0] || {}
      form.name = proxy.$Myfun.setText(AData.name)
      form.is_default = Number(AData.is_default) === 1
      form.telphone = AData.telphone
      form.addrCity = AData.province + ' - ' + AData.city + ' - ' + AData.district
      form.address = AData.address
    })).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  }
}
// ----
const emptyInfo = (event) => {
  const curEL = event.currentTarget
  const input = curEL.parentElement.querySelector('input')
  input.value = ''
  input.dispatchEvent(new Event('input'))
}
const getAuditFun = (type, item) => {
  switch (Number(type)) {
    case 1: {
      const options = {
        type: 3,
        button: ['取消', '确定'],
        initData: myCityData,
        yes: (result) => {
          let resText = ''
          result.forEach((curItem, index) => {
            resText += (index > 0 ? ' - ' : '') + curItem.text
          })
          form.addrCity = resText
        }
      }
      proxy.$Myfun.isIndepth(pickerCity.value, 'open', options)
      break
    }
  }
}
// ----
const setDefault = async () => {
  const arr = addrIds.value
  for (let i = 0; i < Number(arr.length); i++) {
    if (Number(arr[i]) === Number(proxy.$route.query.id)) continue
    await proxy.$http.patch('address/update?id=' + arr[i], {
      is_default: 0,
      // ----
      config_id: userInfo.config_id,
      openid: userInfo.openid
    }).then((res) => {}).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  }
}
const subform = async () => {
  if (Number(form.name.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请填写联系姓名！')
    return false
  }
  if (!isMobile.test(form.telphone)) {
    proxy.$Myfun.forToast(layer.value, 'open', '请填写合法的手机号！')
    return false
  }
  if (Number(form.addrCity.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请选择所在地区！')
    return false
  }
  if (Number(form.address.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请填写收货地址！')
    return false
  }
  // ----
  const forCity = form.addrCity.split(' - ')
  // ----
  let forType = 'post'
  let forUrl = 'address/create'
  let forData = {
    dealer_id: logUser.id || undefined,
    // ----
    name: form.name,
    is_default: form.is_default ? 1 : 0,
    telphone: form.telphone,
    province: forCity[0],
    city: forCity[1],
    district: forCity[2],
    address: form.address,
    // ----
    config_id: userInfo.config_id,
    openid: userInfo.openid
  }
  if (proxy.$route.query.id) {
    forType = 'patch'
    forUrl = 'address/update?id=' + proxy.$route.query.id
    forData = {
      name: form.name,
      is_default: form.is_default ? 1 : 0,
      telphone: form.telphone,
      province: forCity[0],
      city: forCity[1],
      district: forCity[2],
      address: form.address,
      // ----
      config_id: userInfo.config_id,
      openid: userInfo.openid
    }
  }
  // ----
  proxy.$Myfun.onLoading(layerLoading.value, 'open', proxy.$Global.loadingMsg)
  if (form.is_default) await setDefault()
  // ----
  let resData = ''
  await proxy.$http[forType](forUrl, forData).then((res) => { resData = res }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // ----
  proxy.$Myfun.disLoading(layerLoading.value, 'close')
  if (resData) proxy.$router.back()
}
const goback = () => { proxy.$router.back() }

/* ---- */
onBeforeMount(() => {
  getFormInfo()
})
onBeforeRouteLeave(() => { proxy.$Myfun.setScrollTop(proxy.$refs.formSection) })
</script>

<template>
  <div class="mescroll-touch" ref="formSection">
    <div class="formSet">
      <ul>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>联系姓名</i>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="" v-model.trim="form.name"/></p>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.name"></em></transition>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>手机号码</i>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="" v-model.trim="form.telphone"/></p>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.telphone"></em></transition>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>所在地区</i>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="" v-model="form.addrCity" @click="getAuditFun(1)" readonly unselectable="on" onfocus="this.blur()"/></p>
            <span class="fa fa-caret-down xw-color-16"></span>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.addrCity"></em></transition>
          </div>
        </li>
        <li>
          <div class="form-are xw-radius-3">
            <h1>收货地址</h1>
            <p><textarea class="tarea-H3" placeholder="" v-model.trim="form.address"></textarea></p>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align xw-flex-justify">
            <i>设置为默认收货地址</i>
            <p class="uct-sel"><input type="checkbox" class="a-switch" v-model="form.is_default"/></p>
          </div>
        </li>
      </ul>
      <div class="form-sub xw-radius-3 xw-bgCL-11 xw-act" @click="subform">确定提交</div>
      <div class="form-sub xw-radius-3 xw-WhiteRed xw-act" @click="goback">取消返回</div>
    </div>
    <picker-view ref="pickerCity"/>
    <layer-view ref="layer"/>
    <layer-view ref="layerLoading"/>
  </div>
</template>

<style scoped>
/* ---- */
.formSet { padding-bottom: 7.4rem; }

/* ---- */
.uct-sel { height: 3rem; overflow: visible; }
</style>
